package junior.db.mapping;

import org.springframework.util.StringUtils;

/**
 * 下划线与驼峰互相转换的TableNameMapper
 * @author bo.wu
 * @CreateDate 2015年6月2日
 */
public class CamelCaseTableMapping implements TableMapping {
	private String tablePrefix = "";
	private String tableSuffix = "";
	private String entityPrefix = "";
	private String entitySuffix = "";

	public String getTablePrefix() {
		return tablePrefix;
	}
	public void setTablePrefix(String tablePrefix) {
		this.tablePrefix = tablePrefix;
	}
	public String getTableSuffix() {
		return tableSuffix;
	}
	public void setTableSuffix(String tableSuffix) {
		this.tableSuffix = tableSuffix;
	}
	public String getEntityPrefix() {
		return entityPrefix;
	}
	public void setEntityPrefix(String entityPrefix) {
		this.entityPrefix = entityPrefix;
	}
	public String getEntitySuffix() {
		return entitySuffix;
	}
	public void setEntitySuffix(String entitySuffix) {
		this.entitySuffix = entitySuffix;
	}

	@Override
	public String entity2TableName(Class<?> entityClass) {
		String entityName = entityClass.getSimpleName();
		return entityName2TableName(entityName);
	}
	
	private String entityName2TableName(String entityName) {
	    int dynamicEntityIndex = entityName.indexOf("$");
        if (dynamicEntityIndex != -1) {
            entityName = entityName.substring(0, dynamicEntityIndex);
        }
		if (StringUtils.hasText(entityPrefix) && entityName.startsWith(entityPrefix)) {
			entityName = entityName.substring(entityPrefix.length());
		}

		if (StringUtils.hasText(entitySuffix) && entityName.endsWith(entitySuffix)) {
			entityName = entityName.substring(0, entityName.length() - entitySuffix.length());
		}
		
		char[] arrays = entityName.toCharArray();
		StringBuilder buffer = new StringBuilder();
		boolean first = true;
		for(char c : arrays) {
			if(Character.isUpperCase(c)) { //大写字母
				if(! first) {
					buffer.append("_");
				}
				buffer.append(Character.toLowerCase(c));
			} else {
				buffer.append(c);
			}
			if(first) first = false;
		}
		return tablePrefix + buffer.toString() + tableSuffix;
	}
	
	@Override
	public String tableName2EntityName(String tableName) {
		if (StringUtils.hasText(tablePrefix) && tableName.startsWith(tablePrefix)) {
			tableName = tableName.substring(tablePrefix.length());
		}

		if (StringUtils.hasText(tableSuffix) && tableName.endsWith(tableSuffix)) {
			tableName = tableName.substring(0, tableName.length() - tableSuffix.length());
		}
		
		String[] spt = tableName.split("_");
		StringBuilder buffer = new StringBuilder();
		for(int i=0; i<spt.length; i++) {
			buffer.append(StringUtils.capitalize(spt[i]));
		}
		return entityPrefix + buffer.toString() + entitySuffix;
	}
	
}
